<template>
  <div class="task-list">
    <van-sticky>
      <div class="select-box">
        <component
          :is="searchTemp"
          placeholder="搜索"
          v-model="filterData.text"
          @onSearch="onRefresh"
        />
      </div>
    </van-sticky>
    <van-pull-refresh v-model="state.refresh" @refresh="onRefresh">
      <div class="total" v-if="state.total">{{ `共有${state.total}条记录` }}</div>
      <van-list
        :loading="state.loading"
        :finished="state.finished"
        :finished-text="state.list?.length !== 0 ? '———— 已经到底了哦 ————' : '' "
        @load="getList"
      >
        <div class="lists" v-if="state.list?.length">
          <component
            :is="taskItem"
            v-for="item in state.list"
            :key="item.id"
            :record="item"
            @click="toDetail(item.id)"
          />
        </div>
        <component
          :is="empty"
          v-if="!state.list?.length && !state.loading"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup>
import { reactive, nextTick } from 'vue'
import empty from '@/components/empty'
import { getTaskList } from '@/service/village'
import taskItem from './components/taskItem.vue'
import searchTemp from '@/components/searchTemp.vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const filterData = reactive({
  text: '',
})

const state = reactive({
  loading: false,
  finished: false,
  total: 0,
  page: 1,
  pageSize: 10,
  list: []
})

const onRefresh = () => {
  state.list = []
  state.page = 1
  state.refresh = false
  state.loading = false
  state.finished = true
  nextTick(() => {
    state.finished = false
  })
}

const getList = async () => {
  const params = {
    pageindex: state.page -  1,
    limit: state.pageSize,
    ...filterData
  }
  try {
    state.loading = true
    const result = await getTaskList(params)
    state.loading = false
    state.list = [...state.list, ...result.data.items]
    state.total = result.data.total
    if (state.page * state.pageSize >= state.total) {
      state.finished = true
    }
    state.page++
  } catch (err) {
    state.loading = false
    state.finished = true
  }
}

const toDetail = id => {
  router.push({
    name: 'task-detail',
    query: {
      id
    }
  })
}

</script>

<style scoped lang="less">
.task-list {
  .total {
    height: 82px;
    line-height: 82px;
    text-align: center;
    color: #696969;
  }
  .select-box {
    background: #fff;
  }
}
</style>
